package com.qezhhnjy.es.first;


import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author zhaoyangfu - 2021/4/8 17:51
 */
@Slf4j
@Component
public class First {

    @Resource
    private RestHighLevelClient client;

    public CreateIndexResponse createIndex(String index) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(index);
        return client.indices().create(request, RequestOptions.DEFAULT);
    }

    public GetIndexResponse getIndex(String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest(index);
        return client.indices().get(request, RequestOptions.DEFAULT);
    }

    public void insertUser(User user) throws IOException {
        IndexRequest request = new IndexRequest();
        request.index("user").id("1004");
        request.source(JSONUtil.toJsonStr(user), XContentType.JSON);

        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

        log.info("response=>{},{},{}", response.getIndex(), response.getId(), response.getResult());
    }

    public void updateUser() throws IOException {
        UpdateRequest request = new UpdateRequest();

        request.index("user").id("1004");

        request.doc(XContentType.JSON, "sex", "🚹");

        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);

        log.info("response=>{},{},{}", response.getIndex(), response.getId(), response.getResult());
    }
}
